package de.intarsys.security.smartcard.smartcardio;

import java.security.Security;
import java.util.List;

import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CardTerminals;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;

public class ListReaders {

	public static void main(String[] args) {
		try {
			new ListReaders().run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() throws Exception {
		Security.insertProviderAt(new SmartcardioProvider(), 1);
		//

		// use "getInstance" to provide more detailed access
		// TerminalFactory factory = TerminalFactory.getInstance("PC/SC", null);

		TerminalFactory factory = TerminalFactory.getDefault();
		CardTerminals terminals = factory.terminals();
		List<CardTerminal> list = terminals.list();
		for (CardTerminal terminal : list) {
			System.out.println("found " + terminal + " named "
					+ terminal.getName());
			
		}
		CardTerminal cardTerminal = list.get(0);
		System.out.println("Card Insert : " + cardTerminal.isCardPresent());
		Card card = cardTerminal.connect("*");
        CardChannel channel = card.getBasicChannel();
        
        channel = this.ThaiREad(channel);
        
		 int cls = 128;
		    int ins = 176;
		    int p1 = 0;
		    int p2 = 4;
		    byte[] length = new byte[] {0, 13};
		    CommandAPDU commandAPDU = new CommandAPDU(cls, ins, p1, p2, length);
		    String text = null;
		    ResponseAPDU responseAPDU = channel.transmit(commandAPDU);
		    byte[] data = responseAPDU.getData();
		    if (data.length != 13) {
//		      String msg = messages.getString("error."+ SCARDERR006);
//		      msg = msg.replaceAll(":field", "PID");
//		      throw new CardException(SCARDERR006 +":"+ msg);
		    }
		    text = new String(data);
		    System.out.println("data >>> " + data.length);


	}
	
	public CardChannel ThaiREad( CardChannel  channel) throws Exception{
		 byte[] THAI_CITIZEN_ID_CARD = new byte[] {111, 8, (byte)160, 0, 0, 0, 84, 72, 0, 1};
	        int cls = 0;
	        int ins = 164;
	        int p1 = 4;
	        int p2 = 0;
	        byte[] length = new byte[] {(byte)160, 0, 0, 0, 84, 72, 0, 1};
	        CommandAPDU commandAPDU = new CommandAPDU(cls, ins, p1, p2, length);
	        ResponseAPDU responseAPDU = channel.transmit(commandAPDU);
	        byte[] data = responseAPDU.getData();
	        
	        System.out.println("Length : " + data.length);
	        
	        return channel;
	}
}
